<script setup>
import {getProject} from "@/api/project";
import {computed, onMounted, reactive, ref} from "vue";
import {
  getRandomColor,
  patchProject,
  getDateStr,
  getWeekList,
  formatDate,
} from "@/views/project-manage/tool";
import {delay} from "@/utils";
import {useRouter} from "vue-router";
import {Refresh,Search} from "@element-plus/icons-vue";
import {toast} from "@/hook/toast";

const loading = ref(true)
const state = reactive({
  contentWidth: 0,
  timeStr: "",
});
const dateRange = ref([]);
const weekList = ref([]);
const users = ref([]);
const list = ref([]);

const rules = computed(() => ({
  keyword: [
    {
      required: true,
      message: '请输入关键字',
      trigger: 'change'
    }
  ]
}))

const router = useRouter()

function toDetail(row) {
  if (row.empty) return
  const {xiangmu_id: id} = row
  router.push({
    name: 'projectDetail',
    query: {id},
  })
}

function dateChange(ev) {
  // showLoading(chatRef.value);
  const [start, end] = ev;
  updateWeekList(start, end);
}

function updateWeekList(start, end) {
  const startDate = new Date(start);
  const endDate = new Date(end);
  let startValue = startDate.getTime();
  const endValue = endDate.getTime();
  const result = [];
  const currentDateStr = getDateStr(new Date());
  while (startValue <= endValue) {
    result.push(formatDate(startValue, currentDateStr));
    startValue += 1000 * 60 * 60 * 24;
  }
  weekList.value = result;
  initData(start, end);
}

async function initData(start, end) {
  const {keyword} = formData.value
  const payload = {
    start_date: start,
    end_date: end,
  }
  if (keyword.length) {
    payload.keyword = keyword
  }
  let resp = await getProject(payload).catch(() => {
  });
  if (!resp) resp = {data:[]}
  const {data} = resp;
  // if (code !== 1) toast({title: msg, type: 'error'});
  const {projectList, userList} = generateResult(data);
  users.value = userList;
  list.value = projectList;
  await delay(500);
  loading.value = false
}

function refreshData() {
  loading.value = true
  const [start, end] = dateRange.value
  initData(start, end)
}

function initWeekList(timestamp) {
  const date = new Date(timestamp);
  const weekIndex = date.getDay();
  let start = 0;
  if (weekIndex === 0) {
    start = 6;
  } else {
    start = weekIndex - 1;
  }
  const weekRes = getWeekList(start, date.getTime(), getDateStr(date));
  weekList.value = weekRes;
  const [startDate] = weekRes;
  const startObj = new Date(startDate.week);
  const endDate = weekRes[weekRes.length - 1];
  const endDateObj = new Date(endDate.week);
  dateRange.value = [getDateStr(startObj), getDateStr(endDateObj)];
  initData(startDate.week, endDate.week);
}

function generateResult(list) {
  if (!list || !list.length) return [];
  const projectList = [],
      userList = [];
  list.forEach((item, index) => {
    const color = getRandomColor(index % 20);
    const {nickname, user_id: id, xiangmu_list} = item;
    const {height, result: projectItem} = patchProject(
        weekList.value,
        xiangmu_list,
        nickname,
        id,
        color
    );
    const userItem = {nickname, id, height, color};
    userList.push(userItem);
    projectList.push(projectItem);
  });
  return {
    projectList,
    userList,
  };
}

const formData = ref({
  keyword: '',
})
const keyword = ref('')
const chatRef = ref(null);
onMounted(() => {
  initWeekList(Date.now());
});
const formRef = ref(null)

function onSearch() {
  formRef.value?.validate(flag => {
    if (!flag) return
    loading.value = true
    const [start, end] = dateRange.value
    initData(start, end)
  })
}

function resetHandle() {
  loading.value = true
  keyword.value = ''
  formRef.value?.resetFields()
  const [start, end] = dateRange.value
  initData(start, end)
}
</script>
<template>
  <div class="project-manage-wrapper" v-loading="loading" ref="chatRef">
    <div
        class="page-wrapper-container_board full box relative flex column"
        :style="{ '--content-width-value': state.contentWidth }"
    >
      <div class="filter box w-100">
        <el-form inline ref="formRef" hide-required-asterisk :model="formData" >
          <el-form-item label="关键词" prop="keyword">
            <el-input v-model="formData.keyword" type="text" @keyup.enter="onSearch" placeholder="请输入关键词"/>
          </el-form-item>
          <el-form-item label="日期">
            <el-date-picker
                v-model="dateRange"
                type="daterange"
                unlink-panels
                range-separator="到"
                @change="dateChange"
                value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-space>
              <el-button :icon="Search" type="primary" @click="onSearch">搜索</el-button>
              <el-button type="danger" @click="resetHandle">重置</el-button>
              <el-button type="success" :icon="Refresh" @click="refreshData">刷新数据</el-button>
            </el-space>
          </el-form-item>
        </el-form>
      </div>
      <div class="relative flex-1 box w-100">
        <div class="absolute inset" id="pageInner">
          <div class="page-container full box relative">
            <div class="label" id="pageLabel">
              <span>人员</span>
            </div>
            <div class="header-wrap">
              <div class="header">
                <div
                    class="week-item"
                    v-for="(item, index) in weekList"
                    :key="index"
                    :class="{ active: item.active }"
                >
                  <span class="week-date">{{ item.label }}</span>
                  <span class="week-value">{{ item.weekText }}</span>
                </div>
              </div>
            </div>

            <div class="list">
              <div class="slider">
                <div
                    class="person-item"
                    v-for="item in users"
                    :style="{ '--height': item.height, '--color': item.color }"
                    :key="item.id"
                >
                  <span>{{ item.nickname }}</span>
                </div>
              </div>
              <div class="content">
                <div
                    class="project-item"
                    v-for="(item, index) in list"
                    :key="index"
                    :style="{ '--height': item.height }"
                >
                  <div
                      class="project-col relative"
                      v-for="(weekKey) in weekList"
                      :key="weekKey.value"
                  >
                    <div
                        class="job-item"
                        v-for="(job, jobIndex) in item[weekKey.value]"
                        :key="jobIndex"
                        @click="toDetail(job)"
                        :style="{
                        '--color': job.color,
                        '--left': job.left,
                        '--top': job.top,
                      }"
                    >
                      <div
                          class="job-item-inner"
                          :class="{ padding: job.is_jiaban,yq:job.is_yanqi }"
                      >
                        <div class="mask-bg" v-if="job.is_yanqi"></div>
                        <div class="job-add-tag" v-if="job.is_jiaban">
                          <span>加班</span>
                        </div>
                        <span>{{ job.xiangmu_name }}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.project-manage-wrapper {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  background: #fff;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
  box-shadow: 0 0 12px rgba(0, 0, 0, 0.12);

  .page-wrapper-container_board {
    --label-width: 88px;
    --label-height: 88px;
    --week-item-width: 88px;
    --week-item-height: 88px;
    --slide-width: 88px;
    --item-width: 88px;
    --item-height: 88px;
    --border-color: #f2f2f2;
    --item-padding: 4px;
    --content-width: calc(1px * var(--content-width-value));
    --tag-height: 28rpx;
    --tag-bg-color: #ff4d4d;
    --week-active-color: #fd9644;
    --yq-color: #c2c2c2;
    padding: 8px;
    box-sizing: border-box;

    .filter {
      background: #FFFFFF;
      padding: 0 24px;

      .inner {
        background-color: #fff;
        border-radius: 8px;
        padding: 8px 16px;
        box-sizing: border-box;
      }

      .date-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 16px;

        .value {
          color: #1677ff;
        }

        &:last-child {
          margin-bottom: 0;
        }
      }
    }

    .page-container {
      background: #f1f1f1;
      overflow-y: scroll;
      // overflow-x: scroll;
      box-sizing: border-box;

      &::-webkit-scrollbar {
        /*滚动条整体样式*/
        width: 6px; /*高宽分别对应横竖滚动条的尺寸*/
        height: 6px;
      }

      &::-webkit-scrollbar-thumb {
        /*滚动条里面深色条*/
        border-radius: 10px;
        box-shadow: inset 0 0 5px rgba(236, 236, 236, 0.1);
        background: #ccc;
      }

      &::-webkit-scrollbar-track {
        /*滚动条里面轨道*/
        box-shadow: inset 0 0 5px rgba(236, 236, 236, 0.1);
        border-radius: 10px;
        background: #ededed;
      }

      .label {
        position: sticky;
        left: 0;
        top: 0;
        width: var(--label-width);
        height: var(--label-height);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 60;
        font-weight: bold;
        color: #15161a;
        margin-top: calc(-1 * calc(var(--week-item-width)));
        background: #fff;
      }

      .header-wrap {
        position: sticky;
        top: 0;
        z-index: 10;
        width: fit-content;

        .header {
          height: var(--label-height);
          background-color: #fff;
          position: sticky;
          top: 0;
          left: var(--label-width);
          padding-left: var(--label-width);
          box-sizing: border-box;
          display: flex;
          flex-flow: row nowrap;
          width: fit-content;

          .week-item {
            display: flex;
            flex-flow: column;
            align-items: center;
            justify-content: center;
            width: var(--item-width);
            height: var(--item-height);
            flex-shrink: 0;
            box-sizing: border-box;
            background: #fff;
            border-radius: 4px;
            overflow: hidden;

            &:nth-child(odd) {
              background: #f7f8fa;
            }

            &.active {
              background-color: var(--week-active-color);
              color: #fff;
            }

            .week-date {
              font-size: 24px;
              font-weight: bold;
            }

            .week-value {
              font-size: 14px;
              margin-top: 4px;
            }

            &:last-child {
              margin-right: 0;
            }
          }
        }
      }

      .list {
        display: flex;
        flex-flow: row nowrap;
        // width: var(--content-width);
        width: fit-content;

        .content {
          word-break: break-all;
          z-index: 1;
          background-color: #f7f8fa;

          .project-item {
            height: calc(1px * var(--height));
            display: flex;
            flex-flow: row nowrap;
            margin-bottom: 16px;

            &:last-child {
              margin-bottom: 0;
            }

            .project-col {
              width: var(--item-width);
              display: flex;
              flex-flow: column;
              background-color: #fff;
              // border-right: 1px solid var(--border-color);
              border-bottom: 1px solid var(--border-color);

              .job-item {
                width: var(--item-width);
                height: var(--item-height);
                box-sizing: border-box;
                border: 1px solid var(--border-color);
                border-right: 0;
                border-bottom: 0;
                display: flex;
                align-items: center;
                justify-content: center;
                padding: var(--item-padding);
                position: absolute;
                left: 0;
                top: 0;
                cursor: pointer;
                transform: translate(
                        calc(1px * var(--left)),
                        calc(1px * var(--top))
                );
                transition: all .1s ease;

                &:hover {
                  box-shadow: 0 0 12px rgba(0, 0, 0, .12);
                }

                .job-item-inner {
                  color: #fff;
                  width: 100%;
                  height: 100%;
                  background-color: var(--color);
                  text-align: center;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  font-size: 14px;
                  border-radius: 4px;
                  overflow: hidden;
                  position: relative;
                  box-sizing: border-box;

                  .mask-bg {
                    position: absolute;
                    left: 0;
                    right: 0;
                    bottom: 0;
                    top: 0;
                    background: rgba(0, 0, 0, .3);
                  }

                  &.yq {
                    outline: 3px solid #f00;
                    //background: rgba(0,0,0,.5);
                    //background-color: var(--yq-color);
                  }

                  &.padding {
                    padding-top: calc(var(--tag-height) + 4px);
                  }

                  .job-add-tag {
                    position: absolute;
                    z-index: 2;
                    left: 0;
                    top: 0;
                    right: 0;
                    height: var(--tag-height);
                    background-color: var(--tag-bg-color);
                    font-size: 12px;
                    color: #fff;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                  }
                }
              }
            }
          }
        }

        .slider {
          position: sticky;
          left: 0;
          top: 120px;
          width: var(--label-width);
          flex-shrink: 0;
          word-break: break-all;
          z-index: 3;
          background-color: #f7f8fa;

          .person-item {
            font-size: 24px;
            height: calc(1px * var(--height));
            box-sizing: border-box;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 16px;
            background-color: var(--color);
            color: #fff;
            writing-mode: vertical-rl;
            letter-spacing: 6px;
            width: var(--label-width);
            white-space: nowrap;

            &:last-child {
              margin-bottom: 0;
            }
          }
        }
      }
    }
  }
}
</style>
